#include "xiaomi_report.h"

//小米设备电量汇报（fz.xiaomi_battery）
void xiaomi_battery_report(void)
{
    afAddrType_t xiaomi_report_DstAddr;
    uint16 value;
    float voltage;
    int xiaomi_voltage;
    ADCIF = 0;   //清ADC 中断标志
    //采用基准电压avdd5:3.3V，通道0，启动AD转化
    ADCCON3 = (0x00 | 0x30 | 0x0f);
    while ( !ADCIF )
    {
        ;  //等待AD转化结束
    }
    
    value = ADCH<< 6;
    value |= ADCL >>2;
    voltage = (float)value/8191*3.45;  
    xiaomi_voltage = (int)(voltage*1000);
    //字符串第一位为数据长度（不包括第一位）,小米电量汇报格式
    uint8 battery_string[] = {0x04,0x01,0x21,0xa9,0x0b};
    
    battery_string[3] = xiaomi_voltage%256;
    battery_string[4] = xiaomi_voltage/256;

    zclReportCmd_t *pReportCmd;
    const uint8 NUM_ATTRIBUTES = 1;  
    pReportCmd = osal_mem_alloc( sizeof(zclReportCmd_t) + ( NUM_ATTRIBUTES * sizeof(zclReport_t) ) );

    pReportCmd->numAttr = NUM_ATTRIBUTES;    
    
    pReportCmd->attrList[0].attrID = 0xff01;
    pReportCmd->attrList[0].dataType = ZCL_DATATYPE_CHAR_STR;
    pReportCmd->attrList[0].attrData = (void *)(&battery_string);
    
    xiaomi_report_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;
    xiaomi_report_DstAddr.addr.shortAddr = 0;
    xiaomi_report_DstAddr.endPoint=1;
    
    zcl_SendReportCmd( 1 , &xiaomi_report_DstAddr, ZCL_CLUSTER_ID_GEN_BASIC, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, false, bdb_getZCLFrameCounter() );

    osal_mem_free( pReportCmd );
}

//小米无线开关，汇报格式
//使用前得注册1，2，两个端口
//传入按键值[1,2]，小米只支持双键的
void xiaomi_key_report(int button_report)
{
    afAddrType_t xiaomi_report_DstAddr;
    zclReportCmd_t *pReportCmd;
    const uint8 NUM_ATTRIBUTES = 1;  
    pReportCmd = osal_mem_alloc( sizeof(zclReportCmd_t) + ( NUM_ATTRIBUTES * sizeof(zclReport_t) ) );

    pReportCmd->numAttr = NUM_ATTRIBUTES;    
    
    pReportCmd->attrList[0].attrID = 0x00;
    pReportCmd->attrList[0].dataType = ZCL_DATATYPE_BOOLEAN;
    pReportCmd->attrList[0].attrData = 0x00;
    
    xiaomi_report_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;
    xiaomi_report_DstAddr.addr.shortAddr = 0;
    xiaomi_report_DstAddr.endPoint=1;
    
    zcl_SendReportCmd( button_report , &xiaomi_report_DstAddr, ZCL_CLUSTER_ID_GEN_ON_OFF, pReportCmd, ZCL_FRAME_CLIENT_SERVER_DIR, false, bdb_getZCLFrameCounter() );

    osal_mem_free( pReportCmd );
}